import store from '@/store'
import APP_CONFIG from '@/config'
import { generateAccessToken } from '@/utils/auth'

uni.$u.http.setConfig((config) => {
  config.baseURL = APP_CONFIG.API_URL
  config.timeout = APP_CONFIG.REQUEST_TIMEOUT
  config.header = { ...(config.header || {}), ...APP_CONFIG.DEFAULT_HEADERS }
  return config
})

uni.$u.http.interceptors.request.use((config) => {
  const accessToken = generateAccessToken()
  const userToken = store.getters['user/userToken']
  const requireAuth = !(config.custom && config.custom.requireAuth === false)

  if (config.method === 'UPLOAD') {
    config.formData = { ...(config.formData || {}), access_token: accessToken }
    if (userToken && requireAuth) {
      config.formData.user_token = userToken
    }
  } else {
    config.data = { ...(config.data || {}), access_token: accessToken }
    if (userToken && requireAuth) {
      config.data.user_token = userToken
    }
  }

  config.header = { ...(config.header || {}), ...(APP_CONFIG.DEFAULT_HEADERS || {}) }
  if (userToken) {
    config.header.Authorization = `Bearer ${userToken}`
    config.header['user-token'] = userToken
  }

  return config
}, (error) => Promise.reject(error))

uni.$u.http.interceptors.response.use((response) => {
  const { statusCode, data } = response
  if (statusCode !== 200) {
    uni.$u.toast(`HTTP ${statusCode}`)
    return Promise.reject(new Error(`HTTP ${statusCode}`))
  }
  if (data && typeof data === 'object' && Object.prototype.hasOwnProperty.call(data, 'code')) {
    if (data.code === 0) {
      return Object.prototype.hasOwnProperty.call(data, 'data') ? data.data : data
    }
    const message = data.msg || '请求失败'
    const err = new Error(message)
    err.code = data.code
    uni.$u.toast(message)
    return Promise.reject(err)
  }
  return data
}, (error) => {
  uni.$u.toast(error?.message || '网络错误')
  return Promise.reject(error)
})
